<?php
require_once 'includes/header.php';
require_once 'includes/functions.php';
require_once 'includes/DatabaseHelper.php';
require_once '../includes/CognitiveModuleManager.php';

// 初始化认知模块管理器
$moduleManager = new CognitiveModuleManager();

// 默认为新增模式
$isEdit = false;
$moduleId = 0;
$module = [
    'module_name' => '',
    'module_key' => '',
    'description' => '',
    'icon' => '📚',
    'display_order' => 0,
    'background_color' => '#FFFFFF',
    'border_color' => '#000000',
    'age_group' => isset($_GET['age_group']) ? $_GET['age_group'] : '3-4',
    'is_active' => 1
];

// 如果是编辑模式，获取模块信息
if (isset($_GET['id'])) {
    $moduleId = intval($_GET['id']);
    $moduleData = $moduleManager->getModuleById($moduleId);
    
    if ($moduleData) {
        $isEdit = true;
        $module = $moduleData;
    } else {
        $_SESSION['error_message'] = '找不到指定的认知模块';
        header('Location: cognitive_modules.php');
        exit;
    }
}

// 处理表单提交
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 获取表单数据
    $moduleData = [
        'module_name' => $_POST['module_name'],
        'module_key' => $_POST['module_key'],
        'description' => $_POST['description'],
        'icon' => $_POST['icon'],
        'display_order' => intval($_POST['display_order']),
        'background_color' => $_POST['background_color'],
        'border_color' => $_POST['border_color'],
        'age_group' => $_POST['age_group'],
        'is_active' => isset($_POST['is_active']) ? 1 : 0
    ];
    
    $success = false;
    $message = '';
    
    // 验证表单数据
    if (empty($moduleData['module_name'])) {
        $message = '模块名称不能为空';
    } elseif (empty($moduleData['module_key'])) {
        $message = '模块标识符不能为空';
    } else {
        // 验证模块标识符唯一性
        $db = Database::getInstance();
        $checkSql = "SELECT COUNT(*) FROM cognitive_modules WHERE module_key = ? AND age_group = ?";
        $params = [$moduleData['module_key'], $moduleData['age_group']];
        
        if ($isEdit) {
            $checkSql .= " AND module_id != ?";
            $params[] = $moduleId;
        }
        
        $count = $db->fetchColumn($checkSql, $params);
        
        if ($count > 0) {
            $message = '该年龄段下已存在相同的模块标识符';
        } else {
            // 保存数据
            if ($isEdit) {
                $success = $moduleManager->updateModule($moduleId, $moduleData);
                $message = $success ? '认知模块更新成功' : '认知模块更新失败';
            } else {
                $newModuleId = $moduleManager->addModule($moduleData);
                $success = $newModuleId > 0;
                $message = $success ? '认知模块添加成功' : '认知模块添加失败';
                
                if ($success) {
                    $moduleId = $newModuleId;
                    $isEdit = true;
                }
            }
        }
    }
    
    if ($success) {
        $_SESSION['success_message'] = $message;
        // 如果是新增并且成功，重定向到编辑页面
        if ($isEdit) {
            header('Location: cognitive_module_edit.php?id=' . $moduleId);
        } else {
            header('Location: cognitive_modules.php?age_group=' . urlencode($moduleData['age_group']));
        }
        exit;
    } else {
        $_SESSION['error_message'] = $message;
        $module = $moduleData; // 回显表单数据
    }
}

// 年龄段选项
$ageGroups = ['3-4', '5-6', '7-8'];

// 页面标题
$pageTitle = $isEdit ? '编辑认知模块' : '添加认知模块';
?>

<h1 class="mb-4"><i class="bi bi-journal-plus"></i> <?php echo $pageTitle; ?></h1>

<!-- 操作区域 -->
<div class="card mb-4">
    <div class="card-body">
        <div class="d-flex justify-content-between">
            <a href="cognitive_modules.php?age_group=<?php echo urlencode($module['age_group']); ?>" class="btn btn-outline-secondary">
                <i class="bi bi-arrow-left"></i> 返回模块列表
            </a>
            <?php if ($isEdit): ?>
                <div>
                    <a href="cognitive_contents.php?module_id=<?php echo $moduleId; ?>" class="btn btn-primary">
                        <i class="bi bi-list-ul"></i> 管理模块内容
                    </a>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<!-- 消息提示 -->
<?php if (isset($_SESSION['success_message'])): ?>
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <?php echo $_SESSION['success_message']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php unset($_SESSION['success_message']); ?>
<?php endif; ?>

<?php if (isset($_SESSION['error_message'])): ?>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <?php echo $_SESSION['error_message']; ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
    <?php unset($_SESSION['error_message']); ?>
<?php endif; ?>

<!-- 编辑表单 -->
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-pencil-square me-1"></i> <?php echo $pageTitle; ?>
    </div>
    <div class="card-body">
        <form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) . ($isEdit ? '?id=' . $moduleId : ''); ?>">
            <!-- 基本信息 -->
            <h5 class="mb-3">基本信息</h5>
            
            <div class="row mb-3">
                <div class="col-md-6">
                    <label for="module_name" class="form-label">模块名称 <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="module_name" name="module_name" value="<?php echo htmlspecialchars($module['module_name']); ?>" required>
                    <div class="form-text">例如：颜色认知、形状认知</div>
                </div>
                
                <div class="col-md-6">
                    <label for="module_key" class="form-label">模块标识符 <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" id="module_key" name="module_key" value="<?php echo htmlspecialchars($module['module_key']); ?>" required pattern="[a-zA-Z0-9_\-]+" <?php echo $isEdit ? 'readonly' : ''; ?>>
                    <div class="form-text">用于URL和文件名，只能包含字母、数字、下划线和短横线，例如：colors、shapes</div>
                </div>
            </div>
            
            <div class="mb-3">
                <label for="description" class="form-label">模块描述</label>
                <textarea class="form-control" id="description" name="description" rows="3"><?php echo htmlspecialchars($module['description']); ?></textarea>
            </div>
            
            <!-- 显示设置 -->
            <h5 class="mb-3 mt-4">显示设置</h5>
            
            <div class="row mb-3">
                <div class="col-md-4">
                    <label for="icon" class="form-label">图标</label>
                    <input type="text" class="form-control" id="icon" name="icon" value="<?php echo htmlspecialchars($module['icon']); ?>">
                    <div class="form-text">可以使用emoji或图标字符，例如：📚 🎨 🔢</div>
                </div>
                
                <div class="col-md-4">
                    <label for="background_color" class="form-label">背景颜色</label>
                    <input type="color" class="form-control form-control-color" id="background_color" name="background_color" value="<?php echo htmlspecialchars($module['background_color']); ?>" title="选择背景颜色">
                </div>
                
                <div class="col-md-4">
                    <label for="border_color" class="form-label">边框颜色</label>
                    <input type="color" class="form-control form-control-color" id="border_color" name="border_color" value="<?php echo htmlspecialchars($module['border_color']); ?>" title="选择边框颜色">
                </div>
            </div>
            
            <div class="row mb-3">
                <div class="col-md-4">
                    <label for="display_order" class="form-label">显示顺序</label>
                    <input type="number" class="form-control" id="display_order" name="display_order" value="<?php echo $module['display_order']; ?>" min="0">
                    <div class="form-text">数字越小越靠前显示</div>
                </div>
                
                <div class="col-md-4">
                    <label for="age_group" class="form-label">适用年龄段</label>
                    <select class="form-select" id="age_group" name="age_group">
                        <?php foreach ($ageGroups as $group): ?>
                            <option value="<?php echo $group; ?>" <?php echo $group == $module['age_group'] ? 'selected' : ''; ?>>
                                <?php echo $group; ?>岁
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="col-md-4">
                    <div class="form-check form-switch mt-4">
                        <input class="form-check-input" type="checkbox" id="is_active" name="is_active" <?php echo $module['is_active'] ? 'checked' : ''; ?>>
                        <label class="form-check-label" for="is_active">是否显示</label>
                    </div>
                </div>
            </div>
            
            <!-- 预览 -->
            <h5 class="mb-3 mt-4">预览效果</h5>
            
            <div class="mb-4">
                <div class="cognitive-card-preview" style="background-color: <?php echo htmlspecialchars($module['background_color']); ?>; border-color: <?php echo htmlspecialchars($module['border_color']); ?>">
                    <div class="preview-icon"><?php echo htmlspecialchars($module['icon']); ?></div>
                    <div class="preview-title"><?php echo htmlspecialchars($module['module_name'] ?: '模块名称'); ?></div>
                    <div class="preview-description"><?php echo htmlspecialchars($module['description'] ?: '这里是模块描述文字...'); ?></div>
                    <div class="preview-button">开始学习</div>
                </div>
            </div>
            
            <!-- 提交按钮 -->
            <div class="mt-4">
                <button type="submit" class="btn btn-primary">
                    <i class="bi bi-save"></i> 保存模块
                </button>
                <a href="cognitive_modules.php?age_group=<?php echo urlencode($module['age_group']); ?>" class="btn btn-outline-secondary ms-2">取消</a>
            </div>
        </form>
    </div>
</div>

<!-- 帮助提示 -->
<?php if (!$isEdit): ?>
<div class="card mb-4">
    <div class="card-header">
        <i class="bi bi-info-circle me-1"></i> 帮助提示
    </div>
    <div class="card-body">
        <p>创建认知模块步骤：</p>
        <ol>
            <li>填写模块基本信息并提交保存</li>
            <li>在模块内添加具体的认知内容</li>
            <li>为每个内容添加示例图片和音频</li>
            <li>添加知识百科内容</li>
        </ol>
        <p>所有内容都支持音频播放功能，您可以在添加内容时上传对应的音频文件。</p>
    </div>
</div>
<?php endif; ?>

<style>
.cognitive-card-preview {
    width: 300px;
    height: 350px;
    border-radius: 15px;
    border: 5px solid;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.cognitive-card-preview:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
}

.preview-icon {
    font-size: 48px;
    margin-bottom: 15px;
    margin-top: 20px;
}

.preview-title {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 10px;
}

.preview-description {
    font-size: 16px;
    margin-bottom: 30px;
    color: #666;
}

.preview-button {
    background-color: #4CAF50;
    color: white;
    padding: 10px 20px;
    border-radius: 30px;
    font-weight: bold;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
    cursor: pointer;
}
</style>

<script>
// 实时预览功能
document.addEventListener('DOMContentLoaded', function() {
    const moduleNameInput = document.getElementById('module_name');
    const descriptionInput = document.getElementById('description');
    const iconInput = document.getElementById('icon');
    const bgColorInput = document.getElementById('background_color');
    const borderColorInput = document.getElementById('border_color');
    
    const previewTitle = document.querySelector('.preview-title');
    const previewDescription = document.querySelector('.preview-description');
    const previewIcon = document.querySelector('.preview-icon');
    const previewCard = document.querySelector('.cognitive-card-preview');
    
    function updatePreview() {
        previewTitle.textContent = moduleNameInput.value || '模块名称';
        previewDescription.textContent = descriptionInput.value || '这里是模块描述文字...';
        previewIcon.textContent = iconInput.value;
        previewCard.style.backgroundColor = bgColorInput.value;
        previewCard.style.borderColor = borderColorInput.value;
    }
    
    moduleNameInput.addEventListener('input', updatePreview);
    descriptionInput.addEventListener('input', updatePreview);
    iconInput.addEventListener('input', updatePreview);
    bgColorInput.addEventListener('input', updatePreview);
    borderColorInput.addEventListener('input', updatePreview);
    
    // 模块标识符自动生成
    if (!<?php echo $isEdit ? 'false' : 'true'; ?>) {
        moduleNameInput.addEventListener('blur', function() {
            const moduleKeyInput = document.getElementById('module_key');
            if (moduleKeyInput.value === '') {
                let key = moduleNameInput.value
                    .toLowerCase()
                    .replace(/[\u4e00-\u9fa5]/g, '') // 移除中文字符
                    .replace(/[^\w\s-]/g, '') // 移除特殊字符
                    .replace(/\s+/g, '-') // 空格转为短横线
                    .replace(/-+/g, '-') // 合并多个短横线
                    .replace(/^-+|-+$/g, ''); // 移除首尾短横线
                
                moduleKeyInput.value = key || 'module';
            }
        });
    }
});
</script>

<?php require_once 'includes/footer.php'; ?> 